package xyf.p07.binsearch;

/**
 * ClassName: P0162_FindPeakElement
 * Description:
 * Author: xyf
 * Date: 9/7/22 5:11 PM
 * Version: 1.0
 **/
public class P0162_FindPeakElement
{
    public int findPeakElement(int[] nums)
    {
        if(nums.length == 1)
        {
            return 0;
        }

        int start = 0;
        int end = nums.length - 1;

        while (start <= end)
        {
            int middle = (end - start) / 2 + start;

            if (middle == 0)
            {
                if (nums[middle] > nums[middle + 1])
                {
                    return middle;
                }
                else
                {
                    start = middle + 1;
                }
            }
            else if (middle == nums.length - 1)
            {
                if (nums[middle] > nums[middle - 1])
                {
                    return middle;
                }
                else
                {
                    end = middle - 1;
                }
            }
            else if (nums[middle] > nums[middle - 1] && nums[middle] > nums[middle + 1])
            {
                return middle;
            }
            else if (nums[middle] < nums[middle - 1])
            {
                end = middle - 1;
            }
            else
            {
                start = middle + 1;
            }
        }
        return -1;
    }
}